<?php

defined('BASEPATH') or exit('No direct script access allowed');



class Welcome extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
    }


    public function index()
    {
        $this->initialinfo();
        $this->groupjunp($this->group);
    }


    //登录
    public function loginAction()
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $where = array();
        $where['username'] = $username;
        $where['password'] = $password;
        $where['webid'] = $this->web_id;
        $result = $this->db->select('*')->from('users')->where($where)->get()->result_array();

        if (count($result) == 0) {
            unset(  $where['username']);
            $where['phone'] = $username;
            $result = $this->db->select('*')->from('users')->where($where)->get()->result_array();
        }


        if (count($result) != 0) {
            if ($result[0]['status'] != 1) {
                $arr['code'] = 1;
                $arr['msg'] = '账户被禁止';
                $this->sendjsonmsg($arr);
            }
            $this->session->username = $result[0]['username'];
            $this->session->islogin = 1;
            $this->session->user_id = $result[0]['id'];
            $arr = array();
            $arr['code'] = 0;
            $arr['msg'] = '登录成功';

                /*  $MYredis = $this->MyRedis();
                  $token=md5('token'.$result[0]['id']);
                  $MYredis->setex($token,12*60*60,serialize($result[0]));*/
                $arr['token'] = session_id();
                $arr['username'] = $result[0]['username'];
                $arr['group'] = $result[0]['group'] ;
                $result[0]['password']="";
                $arr['userinfo'] =$result[0] ;

            $this->setuserinfo($result[0]);
            $this->sendjsonmsg($arr);
        } else {
            $arr = array();
            $arr['code'] = 1;
            $arr['msg'] = '账号或密码错误';
            $this->sendjsonmsg($arr);
        }
    }

    public function loginCheck()
    {

        if (!$this->session->userinfo) {
            $result = $this->tokenlogin();
        } else {
            $result = $this->session->userinfo;
        }
        if ($result) {
            $result['password'] = "";
            $row['userinfo'] = $result;
            $this->sendjsonmsg($row);
        } else {
            $row['code'] = -1;
            $row['msg'] = "未登录";
            $this->sendjsonmsg($row);
        }
    }

    //登录
    public function login()
    {
        $this->load->view('index');
    }

    //退出登陆
    public function loginout()
    {


        $this->session->islogin = 0;
        $this->session->userinfo = "";
        $this->session->user_id = "";
        $this->session->username = "";
        $arr = array();
        $arr['code'] = 0;
        $arr['msg'] = '未登录';
        redirect(site_url() . '/Welcome/register');

    }

    //退出登陆
    public function loginout2()
    {
       /* $header = getallheaders();
        $MYredis = $this->MyRedis();
        $MYredis->del($header['Token']);*/
        $this->session->islogin = 0;
        $this->session->userinfo = "";
        $this->session->user_id = "";
        $this->session->username = "";
        $arr = array();
        $arr['code'] = 0;
        $arr['msg'] = '未登录';
        $this->sendjsonmsg($arr);
    }


    //登录
    public function register()
    {
        if ($this->session->islogin) {
            $this->index();
        }
        $this->load->library('parser');
        $data['titel'] = '登陆';

        $this->load->view('head', $data);
        $this->load->view('login');
    }


    public function sign($key = "")
    {
        $this->reg($key);
    }

    public function reg($key = "")
    {
        if ($this->session->islogin) {
            $this->index();
        }
        $data['titel'] = '注册';
        $data['Invitation']="";
        if (!empty($key)) {
            $tuijian = $this->Url2Key($key);

            if (isset($tuijian[1])) {
                $this->session->recommender_id = $tuijian[1];
            }
            $data['Invitation']=$key;
        }
       // $data['grouplist'] = $this->getgrouplist();
        unset($data['grouplist'][0]);



        $this->load->view('head', $data);
        $this->load->view('reg');
    }


    /**
     * 完成注册
     */
    public function signaction()
    {
        $msg['code'] = 0;
        $row = $this->input->post();

        /*  if (count($row) != 5) {
              $msg['code'] = 1;
              $msg['msg'] = "参数错误";
              $this->sendjsonmsg($msg);
          }*/

        if(isset($row['frominc'])){
            $row['Invitation']=$row['frominc'];
        }
        if(empty($row['Invitation'])){
            $msg['code'] = 1;
            $msg['msg'] = "缺少邀请码(添加客服微信获取邀请码)";
            $this->sendjsonmsg($msg);
        }
        foreach ($row as $id => $v) {
            if (empty($v)) {
                $msg['code'] = 1;
                $msg['msg'] = "缺少参数";
                $this->sendjsonmsg($msg);
            }
            $row[$id] = trim($v);
        }
        if ($row['password1'] != $row['password2']) {
            $msg['code'] = 1;
            $msg['msg'] = "二次密码不一致";
            $this->sendjsonmsg($msg);
        }

      /*  if (strlen($row['phone']) != 11) {
            $msg['code'] = 1;
            $msg['msg'] = "手机格式错误";
            $this->sendjsonmsg($msg);
        }*/
        $row['group'] = 2;
        /* if($row['group']<2 ||$row['group']>6){
             $msg['code']=1;
             $msg['msg']="身份错误";
             $this->sendjsonmsg($msg);
         }*/

        if (strlen(intval($row['username'])) > 15) {
            $msg['code'] = 1;
            $msg['msg'] = "用户名过长";
            $this->sendjsonmsg($msg);
        }
        $this->load->model('Jd_users_model');
        $result = $this->Jd_users_model->GetUserByName($row['username'], "1");
        if (!empty($result)) {
            $msg['code'] = 1;
            $msg['msg'] = "用户名已经存在";
            $this->sendjsonmsg($msg);
        }

     /*   $result = $this->Jd_users_model->GetUserByPhone($row['phone'], "1");
        if (!empty($result)) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号已经存在";
            $this->sendjsonmsg($msg);
        }
        $MYredis = $this->MyRedis();
        $field = $_SERVER['REMOTE_ADDR'];
        $field = explode(".", $field);
        $field = $field[0] . "." . $field[1];
        if ($row['code'] != $MYredis->get($field)){
            $msg['code'] = 1;
            $msg['msg'] = "验证码错误";
            if ($field != '114.100' && $field != '183.160' && $row['code'] != '111111') {
                $this->sendjsonmsg($msg);
            }
        }
        if ($row['phone'] != $MYredis->get($field . "phone")) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号不一致";
            if ($field != '114.100' && $row['code'] != '111111') {
                $this->sendjsonmsg($msg);
            }
        }*/
        $row['password'] = $row['password1'];
        unset($row['password1']);
        unset($row['password2']);


        if(isset($row['Invitation'])){
            $tuijian = $this->Url2Key($row['Invitation']);
            if (isset($tuijian[1])) {
                $this->session->recommender_id = $tuijian[1];
            }else{
                $msg['code'] = 1;
                $msg['msg'] = "邀请码错误(添加客服微信获取邀请码)";
                $this->sendjsonmsg($msg);
            }
        }
        unset($row['Invitation']);
        if (!empty($this->session->recommender_id)) {
            $result = $this->Jd_users_model->GetUserById($this->session->recommender_id, "username");
            if (!empty($result)) {
                $row['recommender'] = $result['username'];
                $row['recommender_id'] = $this->session->recommender_id;
                $row['salername'] = $result['username'];
            }else{
                $msg['code'] = 1;
                $msg['msg'] = "邀请码错误";
                $this->sendjsonmsg($msg);
            }
        }
        $row['regtime'] = time();

        /*  if($field=='114.100'|| $field='183.160'){
              $row['iskefu'] =1;
          }else{
              $row['iskefu'] =0;
          }*/
        $row['iskefu'] = 0;
        unset($row['code']);
        $result = $this->Jd_users_model->adduser($row);
        if ($result) {
            $msg['code'] = 0;
            $msg['msg'] = "注册成功";
            $this->session->islogin = 1;
            $this->session->user_id = $result;
            $this->session->username = $row['username'];
            $this->RecommenderTotal($result, $row);//推荐人奖励发放
            $this->sendjsonmsg($msg);
        }
        $msg['code'] = 1;
        $msg['msg'] = "注册失败";
        $this->sendjsonmsg($msg);
    }


    //对变量进行json编码
    private function ajaxResult($data)
    {
        echo json_encode($data);
        die;
    }


    private function RecommenderTotal($result, $row = '')
    {


        if ($this->session->recommender_id) {

            $this->addRecommendelog($result, $row);
            /*  $newrow = array();
              $newrow['user_id'] = $this->session->recommender_id;
              $newrow['gold'] = 10;
              $this->moneyupdate($newrow, 3, $result);*/
            $newrow = array();
            $newrow['extension'] = 10;
            $newrow['extension_nub'] = 1;
            $newrow['extension_nub_day'] = 1;
            $newrow['update'] = date('Y-m-d');
            $this->UpdataUserinfo($newrow, $this->session->recommender_id);
        }


        $this->session->recommender_id = '';
    }


    public function addRecommendelog($user_id2, $row)
    {
        /*  $row['user_id']=2;
          $row['username']='商户';*/
        $this->load->model('Jd_users_model');
        $user_id = $this->session->recommender_id;
        $result = $this->Jd_users_model->GetUserById($user_id, 'username');
        $name = $result['username'];
        $name2 = $row['username'];
        $this->load->model('Jd_Recommended_log');

        $newrow['user_id'] = $user_id;
        $newrow['username'] = $name;
        $newrow['Recommended_id'] = $user_id2;
        $newrow['Recommended'] = $name2;
        $newrow['addtime'] = date('Y-m-d H;i;s');
        $this->Jd_Recommended_log->addlog($newrow);
    }


    public function generate_captcha()
    {
        $this->load->library('captcha');

        $config = [
            'seKey' => 'Zell Dincht',          // 验证码加密密钥
            'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',             // 验证码字符集合
            'expire' => 1800,                   // 验证码过期时间（s）
            'useZh' => FALSE,                  // 使用中文验证码
            'useImgBg' => FALSE,                  // 使用背景图片
            'fontSize' => 18,                     // 验证码字体大小(px)
            'useCurve' => TRUE,                   // 是否画混淆曲线
            'useNoise' => FALSE,                  // 是否添加杂点
            'imageW' => 120,                      // 验证码图片宽度
            'imageH' => 40,                     // 验证码图片高度
            'length' => 4,                      // 验证码位数
            'fontttf' => 'texb.ttf',                // 验证码字体，不设置随机获取
            'bg' => array(243, 251, 254),   // 背景颜色
            'reset' => TRUE,                   // 验证成功后是否重置
        ];
        $captcha = new Captcha($config);
        $captcha->generate();
    }

    public function checkcode()
    {
        $this->load->library('captcha');
        if (!empty($code = $this->input->post('captcha'))) // 用户输入的验证码，根据逻辑，自行处理吧，大概就是这么个意思。
        {
            $captcha = new Captcha();
            $result = $captcha->validate($code);// 验证
            if ($result) {
                $data['success_info'] = '验证成功';
            }
        }
    }

    /**
     * 发送手机验证码
     */
    public function sendcode()
    {
        $row = $this->input->post();
        $result = $this->check_phone($row['phone']);
        if (!$result) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号码格式错误";
            $this->sendjsonmsg($msg);
        }
        $this->load->model('Jd_users_model');
        $result = $this->Jd_users_model->GetUserByPhone($row['phone'], "1");
        if (!empty($result)) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号已经存在";
            $this->sendjsonmsg($msg);
        }
        $MYredis = $this->MyRedis();
        $field = $_SERVER['REMOTE_ADDR'];
        $field = explode(".", $field);
        $field = $field[0] . "." . $field[1];
        $ttl = $MYredis->ttl($field);
        if ($ttl > 840) {
            $msg['code'] = 1;
            $msg['msg'] = "发送最小间隔为1分钟";
            $this->sendjsonmsg($msg);
        }
        $code = rand(100000, 999999);
        $result = $this->send($row['phone'], $code);
        if (!$result) {
            $msg['code'] = 1;
            $msg['msg'] = "发送失败";
            $this->sendjsonmsg($msg);
        }
        $MYredis->setex($field, 60 * 15, $code);
        $MYredis->setex($field . "phone", 60 * 15, $row['phone']);
        $msg['code'] = 0;
        $msg['msg'] = "发送成功";
        //$msg['date'] = $code;
        $this->sendjsonmsg($msg);
    }

    /**
     * 检查手机号码
     */
    public function checkphone()
    {
        $row = $this->input->post();
        $result = $this->check_phone($row['phone']);
        if (!$result) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号码格式错误";
            $this->sendjsonmsg($msg);
        }
        $this->load->model('Jd_users_model');
        $result = $this->Jd_users_model->getByRow($row, 'id');

        if (!empty($result)) {
            $msg['code'] = 1;
            $msg['msg'] = "手机号已经存在";
            $this->sendjsonmsg($msg);
        } else {
            $this->sendjsonmsg();
        }
    }

    public function send($phone, $code)
    {


        $result= $this->sendMSG($phone,$code);
        if (@$result['code'] == 0 || @$result['Code'] == 0) {
            return true;
        }
        //$result = $this->sendSms($phone, $code);
        $result=file_get_contents('http://101.37.76.120/Welcome/send2/'.$phone.'/'.$code);
        $result=json_decode($result,true);
        if (@$result['code'] == 'OK' || @$result['Code'] == 'OK') {
            return true;
        }

        return false;
    }

    public function send2($phone, $code)
    {
        $result = $this->sendSms($phone, $code);
        $this->sendjsonmsg($result);
    }

    function check_phone($phone)
    {
        $check = '/^(1(([123456789][0-9])|(47)))\d{8}$/';
        if (preg_match($check, $phone)) {
            return true;
        } else {
            return false;
        }
    }


    function senorder(){
        $this->load->view('senorder');
    }




    function excelToArray()
    {
        $row = $this->input->post();
        $crawlerInfo=$row['crawlerInfo'];

        $url='https://mms.pinduoduo.com/sydney/api/mallFlow/queryMallFlowOverView';
       // $curlPost['beginDate']='2020-12-23';
        $curlPost['crawlerInfo']=$crawlerInfo;
        //$curlPost['endDate']='2020-12-29';

        $url='https://mms.pinduoduo.com/sydney/api/goodsDataShow/queryGoodsPagePlnOstList';

      /*  $curlPost=array();
        $curlPost['pageSize']=5;
        $curlPost['pageNo']='1';
        $curlPost['resourceTypes']='1,2,3';*/
        $header  = array(
            'anti-content:'.$crawlerInfo,
            'Content-Type:'.'application/json;charset=UTF-8',
            'cookie:'.'api_uid=rBQRw1/d0qB+9UQA01iyAg==; _nano_fp=XpEol0X8X5UoX0T8n9_I6hwwBEQT8Nz_KdbcI9yx; _bee=SpCiYOjAIWguQxLKf2I98QlzzKZi6DEc; _f77=9e4df1c7-8bdf-457d-88e7-d892b2ea6135; _a42=76556fd2-ba4f-4227-bd38-2a5f936c4ac7; rckk=SpCiYOjAIWguQxLKf2I98QlzzKZi6DEc; ru1k=9e4df1c7-8bdf-457d-88e7-d892b2ea6135; ru2k=76556fd2-ba4f-4227-bd38-2a5f936c4ac7; mms_b84d1838=120,3397,1202,1203,1204,1205; PASS_ID=1-f/IJ3NyOaHf4GCF3zNPxsJIPcsQm9m5vE6OHclR5H/LnidEEc2Gyv6J2wSfrGjyinr8wmIoHBcUvmob2lK2puw_922617827_75103469; JSESSIONID=063DC47A5504B65FC4F99EEE1721CFB3; x-visit-time=1609309925724'
        );
        $curlPost=json_encode($curlPost);



       // $curlPost='{"v":1,"t":1609310853972,"r":"690429","c":3708490795,"d":[{"t":1609310852971,"tu":"https://mms.pinduoduo.com/sydney/api/mallFlow/queryMallFlowOverView","n":0,"pl":1,"c":200,"rt":55,"q":783,"p":1192,"e":{"mall_id":922617827,"user_id":75103469,"vip":"211.159.221.123"}}]}';


      $res=  $this->curl_post($url,$curlPost,$header);


var_dump($res);

    }

    public function getconfiglist()
    {
        $name = $this->input->post('name');
        if ($name == 'group') {
            $res = $this->GetCachData('getgrouplist');
        }
        if ($name == 'team') {
            $res = $this->GetCachData('getteamlist');
        }
        if ($name == 'channel') {
            $res = $this->GetCachData('getchannellist');
        }

        $msg['code'] = 0;
        $msg['list'] = $res;
        $this->sendjsonmsg($msg);
    }

    public function changepasswordbyold()
    {
        $msg['code'] = 0;
        $row = $this->input->post();
        if (!$this->session->islogin) {
            $msg['code'] = 1;
            $msg['msg'] = "请先登录";
            $this->sendjsonmsg($msg);
        }


        foreach ($row as $id => $v) {
            if (empty($v)) {
                $msg['code'] = 1;
                $msg['msg'] = "缺少参数";
                $this->sendjsonmsg($msg);
            }
            $row[$id] = trim($v);
        }
        if ($row['oldpassword'] != $this->session->userinfo['password']) {
            $msg['code'] = 1;
            $msg['msg'] = "旧密码错误";
            $this->sendjsonmsg($msg);
        }
        if ($row['password'] != $row['secondpwd']) {
            $msg['code'] = 1;
            $msg['msg'] = "二次密码不一致";
            $this->sendjsonmsg($msg);
        }

        $userinfo = array();
        $userinfo['user_id'] = $this->session->user_id;
        $userinfo['password'] = $row['password'];
        $this->load->model('fl_users_model');
        $res = $this->fl_users_model->updata_user($userinfo);
        if ($res) {
            $msg['code'] = 0;
            $msg['msg'] = "修改成功";
            $this->sendjsonmsg($msg);
        }
        $msg['code'] = 1;
        $msg['msg'] = "修改失败";
        $this->sendjsonmsg($msg);
    }
}
